import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/my/asset_type_enum.dart';
import 'package:hktk_app/model/industry/exam_model.dart';
import 'package:hktk_app/pages/mine/child/res_view_page.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/mine/bank_title_widget.dart';
import 'package:hktk_app/widget/page_title_widget.dart';

/// 我的课程页面
class MyCoursePage extends StatefulWidget {
  const MyCoursePage({super.key});

  @override
  State<MyCoursePage> createState() => _MyCoursePageState();
}

class _MyCoursePageState extends State<MyCoursePage>
    with TickerProviderStateMixin {
  late BuildContext _context;

  /// 初始化数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// tab控制器
  late TabController _tabController;

  /// 对应数据方法
  late List<ExamModel> _list;

  /// 判断控制器是否创建成功
  late bool _createTab;

  @override
  void initState() {
    super.initState();

    _list = [];
    _createTab = false;
    _futureInit = _initData();
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("myCoursePage 页面 -> dispose 方法执行 ===> ");
    debugPrint("");
    if (_createTab) {
      _tabController.dispose();
    }
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    return Scaffold(
      backgroundColor: colorWhite2,

      body: SafeArea(child: Column(
        children: [
          PageTitleWidget(name: "我的课程", pageContext: context),
          Expanded(child: _futureItem()),
        ],
      )),
    );
  }

  /// 加载组件
  Widget _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder:
          (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          var map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          // 加载中
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {

      _list = await MyDao.myBuyExam();
      if (_list.isNotEmpty) {
        // 初始化控制器
        _tabController = TabController(length: _list.length, vsync: this);
        _createTab = true;
      }
      map["suc"] = true;
    } catch (e) {
      debugPrint("myCoursePage 页面 -> 初始化方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("myCoursePage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示组件
  Widget _content() {
    if (_list.isNotEmpty) {
      return Column(
        children: [
          hiSpace(height: 30),
          BankTitleWidget(
            tabController: _tabController,
            tabList: _list.map((v) => v.name!).toList(),
          ),
          hiSpace(height: 30),
          Expanded(child: _conViewItem()),
        ],
      );
    } else {
      return Center(
        child: Text(
          "暂无数据",
          style: FontUtil.fontGrey1(28),
        ),
      );
    }
  }

  _conViewItem() {
    double bottom = MediaQuery.of(_context).padding.bottom;
    return Container(
      margin: EdgeInsets.only(bottom: bottom),
      child: TabBarView(
        controller: _tabController,
        children: _viewItems(),
      ),
    );
  }

  /// 内容组件
  _viewItems() {
    List<Widget> widgets = [];
    for (ExamModel exam in _list) {
      List<int> cIds = exam.categorys!.map((v) => v.id!).toList();
      widgets.add(ResViewPage(
        type: AssetTypeEnum.video,
        categoryIds: cIds.join(","),
        exam: exam,
      ));
    }
    return widgets;
  }
}
